<template>
  <el-dialog v-model="addDialog" title="添加题库" width="500">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="题库名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" clearable autocomplete="off" />
      </el-form-item>
      <el-form-item label="题库描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" type="textarea" :rows="3" autocomplete="off" />
      </el-form-item>
      <el-form-item label="所属学科" :label-width="formLabelWidth" prop="subjectId">
        <el-select v-model="form.subjectId" placeholder="请选择" style="width: 240px">
          <el-option v-for="item in options" :key="item.id" :label="item.subjectName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
        <el-input-number v-model="form.sort" :min="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import axios from '@/axios/index.js'
import { useStaffStore } from '@/stores/staff'
import { ElMessage } from 'element-plus'

const formLabelWidth = '140px'
let addDialog = defineModel("addDialog")
let emit = defineEmits(['getQuestionsBankList'])
const ruleFormRef = ref()
const rules = ref({
  name: [
    { required: true, message: '请输入题库名称', trigger: 'blur' },
    { min:1,max:100, message: '题库名称长度必须在1-100字以内', trigger: 'blur' },
  ],
  subjectId: [{ required: true, message: '请选择学科', trigger: 'blur' }],
})
const form = ref({
  name: '',
  description: '',
  subjectId: '',
  staffId: '',
  status: 0,
  sort: 1
})

const options = ref([])

//保存
let save = function () {
  form.value.staffId = useStaffStore().staffInfo.staff.id
  axios.post(`/api/v1/admin/question/banks`, form.value, { headers: { 'content-type': 'application/json' } }).then(response => {
    ElMessage({
      type: 'success',
      message: response.data.message
    })
    emit('getQuestionsBankList', -1, -1, null)
    addDialog.value = false
  })
}

//查询所有学科
let getSubjectList = function () {
  axios.get(`/api/v1/admin/subject/list`, {
    params: {
      currentPage: 1,
      pageSize: -1
    }
  }).then(response => {
    options.value = response.data.data.records
  })
}

onMounted(() => {
  getSubjectList()
})

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      save()
    }
  })
}

</script>

<style scoped></style>